package com.xexun.gpstracker.base;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.xexun.gpstracker.vo.FlavorType;
import org.simple.eventbus.Subscriber;

import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.AppManager;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.component.MessageSender;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.inter.CommCallback;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.pojo.*;
import com.xexun.gpstracker.service.BlueToothAntiLostService;
import com.xexun.gpstracker.service.CommunicationService;
import com.xexun.gpstracker.ui.LoginActivity;
import com.xexun.gpstracker.util.ByteUtil;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.vo.Msg;
import com.xexun.gpstracker.vo.Session;

/**
 * Created by HH
 * Date: 2015/7/17 0017
 * Time: 上午 9:48
 */
public class BaseActivity extends Activity {

    protected static InputMethodManager imm;
    private Long lastChatMsgId = 0L;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AppManager.getAppManager().addActivity(this);
        AppContext.getEventBus().register(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        AppManager.getAppManager().deleteLastActivity();
        AppContext.getEventBus().unregister(this);
        super.onDestroy();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        hideInputBoard();
        return super.onTouchEvent(event);
    }

    public void hideInputBoard() {
        IBinder binder = getCurrentFocus() == null ? new Binder() : getCurrentFocus().getApplicationWindowToken();
        if (imm == null) {
            imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        }
        if (imm != null) {
            imm.hideSoftInputFromWindow(binder, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 更新设备列表缓存
     *
     * @param msg
     */
    @Subscriber(tag = Constants.EVENT_TAG_TERM_STATUS)
    private void updateTermStatus(Msg msg) {
        if (msg == null || msg.getFrom() == null) {
            return;
        }
        String imei = msg.getFrom();
        int status = ByteUtil.byteArrayToInt(msg.getData());
        List<Device> devices = Session.getInstance().getMonitors();
        for (Device device : devices) {
            if (imei.equals(device.getImei())) {
                device.setOnline(status);
                break;
            }
        }
        Session.getInstance().setMonitors(devices);
    }

    @Subscriber(tag = Constants.EVENT_TAG_TERM_STATUS_BATCH)
    private void updateTermStatusBatch(Map<String, Integer> stateMap) {
        if (stateMap == null || stateMap.isEmpty()) {
            return;
        }
        List<Device> devices = Session.getInstance().getMonitors();
        for (Device device : devices) {
            if (stateMap.containsKey(device.getImei())) {
                device.setOnline(stateMap.get(device.getImei()));
            }
        }
        Session.getInstance().setMonitors(devices);
        Session.getInstance().setChanged();
        Session.getInstance().notifyObservers();
    }

    @Subscriber(tag = Constants.EVENT_TAG_TERM_BIND)
    private void updateTermBindStatus(Msg msg) {
        if (msg == null || msg.getFrom() == null) {
            return;
        }
        String imei = msg.getFrom();
        int status = ByteUtil.byteArrayToInt(msg.getData());
        Session session = Session.getInstance();
        List<Device> devices = session.getMonitors();
        Iterator<Device> it = devices.iterator();
        while (it.hasNext()) {
            Device device = it.next();
            if (imei.equals(device.getImei())) {
                if (status == 1) {
                    device.setBinded(true);
                } else {
                    it.remove();
                    CommUtil.showMsgShort(getString(R.string.term_bind_refuse));
                }
                break;
            }
        }
        session.setMonitors(devices);
        session.setChanged();
        session.notifyObservers();
    }

    @Subscriber(tag = Constants.EVENT_TAG_TERM_FRIEND)
    private void updateTermFriend(Msg msg) {
        if (msg == null || msg.getFrom() == null) {
            return;
        }
        String res = new String(msg.getData());
        String[] array;//格式： id:0 or id:1
        if (CommUtil.isBlank(res) || (array = res.split(":")).length != 2) {
            Log.i(BaseActivity.class.getName(), "收到无效终端绑定信息，直接忽略");
            return;
        }
        Session session = Session.getInstance();
        List<TermFriend> friends = session.getFriendList();
        Iterator<TermFriend> it = friends.iterator();
        while (it.hasNext()) {
            TermFriend f = it.next();
            if (array[0].trim().equals(Integer.valueOf(f.getId()).toString())) {
                if ("1".equals(array[1].trim())) {
                    f.setBind(1);
                } else {
                    it.remove();
                }
                break;
            }
        }
        session.setFriendList(friends);
        session.setChanged();
        session.notifyObservers();
    }

    @Subscriber(tag = Constants.EVENT_TAG_OFFLINE_NOTIFY)
    private void updateOfflineStatus(Object obj) {
        if (obj instanceof Msg) {
            Msg msg = (Msg) obj;
            if (CommUtil.isNotBlank(msg.getFrom()) && !msg.getFrom().equals(Session.getInstance().getImei())) {
                return;
            }
        }
        AppContext.forceLogout = true;
        CommunicationService cs = CommunicationService.get();
        if (cs != null) {
            cs.onDestroy();
        }

        logout(true);


        clear();
    }

    @Subscriber(tag = Constants.EVENT_TAG_INTERVAL_WARN)
    private void intervalWarn(ChatMsg chatMsg) {
        lastChatMsgId = chatMsg.getId();
        CommUtil.delayExecute(5000, callback);
    }

    private CommCallback callback = new CommCallback() {
        @Override
        public void execute() {
            super.execute();
            if (lastChatMsgId == null) {
                return;
            }
            try {
                ChatMsg chatMsg = AppContext.db.findById(ChatMsg.class, lastChatMsgId);
                if (chatMsg == null || chatMsg.getIsRead() == 1) {
                    return;
                }
                Uri uri = Uri.parse(Constants.SCHEME_RES + R.raw.alarm);
                Utils.playSoundAndVibrate(BaseActivity.this, uri);
                SharedPreferences sp = Utils.getPreferences(BaseActivity.this);
                boolean keep = sp.getBoolean(Constants.MSG_VOICE_KEEP, true);
                if (keep) {
                    CommUtil.delayExecute(Constants.INTERVAL_WARN_TIME, callback);
                }
            } catch (Exception e) {
                Log.e(BaseActivity.class.getName(), "Interval warn query failed.", e);
            }
        }
    };

    /**
     * 退出
     */
    public void logout(final Boolean isLoginOther) {
        User.logout(this, new HttpCallback() {
            @Override
            public void onStart() {
                WizardAlertDialog.getInstance().showProgressDialog("", Session.getInstance().getMainActivity());
            }

            @Override
            public void onFinish() {
                WizardAlertDialog.getInstance().closeProgressDialog();
            }

            @Override
            public void onSuccess(ResponseData obj) {
                if(Constants.FLAVOR  != FlavorType.PHONELOC) {  //退出应用不关闭后台服务
                    clear();
                    Session.getInstance().clearData();
                    AppContext.isEntered = false;
                }
                AppContext.forceLogout = false;
                AppContext.managerInfoChecked = false;
                Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
                if (isLoginOther){
                    intent.putExtra(LoginActivity.LoginInfo, LoginActivity.LoginOther);
                }
                BaseActivity.this.startActivity(intent);
                BaseActivity.this.finish();
            }

            @Override
            public void onFailure(String message) {
                if (CommUtil.isNotBlank(message)) {
                    Toast.makeText(BaseActivity.this, message, Toast.LENGTH_SHORT).show();
                }
                onSuccess(null);
            }
        });
    }

    private void clear() {
        Intent commIntent = new Intent(BaseActivity.this, CommunicationService.class);
        stopService(commIntent);
        Intent bleIntent = new Intent(this, BlueToothAntiLostService.class);
        stopService(bleIntent);
    }

    public void sendHeartBeat() {
        if (CommunicationService.isConnected) {
            MessageSender.getInstance().sendHeartBeatSingle();
        } else {
            Intent commIntent = new Intent(BaseActivity.this, CommunicationService.class);
            startService(commIntent);
        }
    }

    public View getRootView() {
        return ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
    }
}
